# coding: utf-8
import hashlib
from urllib.parse import quote, quote_plus

import requests
from filecache import filecache, YEAR

# 切勿泄漏 AK & SK！
AK = '<replace me>'
SK = '<replace me>'

BASE_API = 'http://api.map.baidu.com'
LOCATION_API = '/geocoding/v3/?address={}&city={}&output=json&ak={}'


# 加缓存，避免重复查询
@filecache(YEAR)
def get_location(addr, city=''):
    """
    文档参考：http://lbsyun.baidu.com/index.php?title=webapi/guide/webservice-geocoding
    """
    if not addr:
        return dict(lng=0.0, lat=0.0)

    url = _get_query_url(LOCATION_API.format(addr, city, AK))
    r = requests.get(url)
    result = r.json()
    assert result['status'] == 0, u"获取经纬度信息失败！请求：{}，返回结果：{}".format(url, result)
    return result['result']['location']


def _get_query_url(query_str):
    query_str = query_str.replace('#', '')  # 去除特殊字符
    # 对 query_str 进行转码，safe 内的保留字符不转换
    qs = quote(query_str, safe="/:=&?#+!$,;'@()*[]")
    sn = hashlib.md5(quote_plus(qs + SK).encode('utf8')).hexdigest()
    return BASE_API + query_str + f'&sn={sn}'


if __name__ == '__main__':
    print(get_location('安徽省合肥市长丰县水湖镇长寿西路177号（长丰一中西200米处）', '安徽合肥'))
